package com.it.sendmail.Controller;


import com.it.sendmail.Dao.MailBean;
import com.it.sendmail.Dao.RespBean;
import com.it.sendmail.Dao.User;
import com.it.sendmail.Utils.MailUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;

@Controller
public class Mail {

    @Resource
    private MailUtil mailUtil;

   @Resource
    private TemplateEngine templateEngine;

    @PostMapping("/mails")
    @ResponseBody
    public RespBean doMail(User user){
        System.out.println("数据: " + user);
        if (user != null){
            MailBean mailBean = new MailBean();
            mailBean.setRecipient(user.getMailbox());//接收者
            mailBean.setSubject("用户信息");//标题
            //内容主体
            String code = UUID.randomUUID().toString().substring(0,5);
            mailBean.setContent("SpringBootMail发送一个简单格式的邮件，时间为：" +code+ new Date());

            mailUtil.sendSimpleMail(mailBean);
            return RespBean.success("查询成功",user);
        }
        return RespBean.error("发送失败！");
    }


    @PostMapping("/mails2")
    @ResponseBody
    public RespBean doMail2(User user){
        System.out.println("数据: " + user);
        //以HTML模板发送邮件
        if (user != null){
            //注意：Context 类是在org.thymeleaf.context.Context包下的。
            Context context = new Context();
            //html中填充动态属性值
            context.setVariable("username", "码农用户");
            context.setVariable("url", "https://www.aliyun.com/?utm_content=se_1000301881");
            //注意：process第一个参数名称要和templates下的模板名称一致。要不然会报错
            //org.thymeleaf.exceptions.TemplateInputException: Error resolving template [email]
            String emailContent = templateEngine.process("email", context);

            MailBean mailBean = new MailBean();
            mailBean.setRecipient(user.getMailbox());
            mailBean.setSubject("主题：这是模板邮件");
            mailBean.setContent(emailContent);

            mailUtil.sendHTMLMail(mailBean);
            return RespBean.success("查询成功",user);
        }
        return RespBean.error("发送失败！");
    }


}
